﻿namespace TomatoBreak.Infrastructure
{
    using System;
    using System.Web;
    using System.Configuration;

    using Castle.MicroKernel.Registration;
    using Castle.MicroKernel.SubSystems.Configuration;
    using Castle.Windsor;

    using NHibernate;

    using DataAccess;

    public class DataAccessInstaller : IWindsorInstaller
    {
        public virtual void Install(IWindsorContainer container, IConfigurationStore store)
        {
            if (container == null)
            {
                throw new ArgumentNullException("container");
            }

            var debugMode = container.Resolve<HttpContextBase>().IsDebuggingEnabled;
            var connectionStringName = debugMode ? "Development" : "Production";

            var connectionStringSetting = ConfigurationManager.ConnectionStrings[connectionStringName];

            container.Register(Component.For<SessionProvider>().UsingFactoryMethod(k => new SessionProvider(connectionStringSetting.ConnectionString, connectionStringSetting.ProviderName)).LifeStyle.PerWebRequest)
                     .Register(Component.For<ISession>().UsingFactoryMethod(k => k.Resolve<SessionProvider>().GetSession()).LifeStyle.PerWebRequest)
                     .Register(Component.For(typeof(IRepository<>)).ImplementedBy(typeof(Repository<>)).LifeStyle.PerWebRequest);

            if (debugMode)
            {
                container.Resolve<SessionProvider>().CreateSchema();
            }
        }
    }
}